<?php

namespace App\Http\Middleware;

use Closure;
use App\Http\Lib\Output;
use App\Traits\Response as ResponseTrait;
use App\Http\Lib\UserLib;
use App\Http\Lib\Util;
use Illuminate\Database\Eloquent\Model;
use App\Models\AccessLog;

class TokenAuth
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $ue = UserLib::getUserFromToken($request);
        //dd($ue);
        if(empty($ue)) {
            $site_id = 0;
            $url = Util::genUrl(env('USERCENTER_LOGIN_URL'));
            return response()->json(['errcode' => 401, 'errmessage'=> '用户未登录,请在用户中心登录', 'url' => $url]);
        }
        
//         $isGetMethod = $request->isMethod('GET');      
//         if($ue->ban != USER_UNBAN){
//                 return $this->e(ERROR_USER_BANED);
//         }
        
        $path = $request->path();
//         $cur_siteId0 = $request->header('Cur-Site-Id', SITEID_TJ);
//         $cur_siteId = $request->input('site-id', $cur_siteId0);
        
        // access log
        $log = new AccessLog();
        $log->type = 'user';
        $log->user_id = $ue->id;
        $log->api = $path;
        $log->params = json_encode($request->all(), JSON_UNESCAPED_UNICODE);
        $log->ip = $request->ip();
        $log->save();
        return $next($request);
    }
}
